package com.tanhua.mongo.api;

import com.tanhua.dubbo.api.FriendApi;
import com.tanhua.model.mongo.Friend;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

@DubboService
public class FriendApiImpl implements FriendApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 添加联系人
     *
     * @param friendId
     * @param userId
     */
    @Override
    public void saveFriend(Long friendId, Long userId) {
        //判断是否关联好友
        Query query1 = Query.query(Criteria.where("userId").is(userId).and("friendId").is(friendId));
        Friend friend1 = mongoTemplate.findOne(query1, Friend.class);
        if (friend1 == null){
            Friend friend = new Friend();
            friend.setUserId(userId);
            friend.setFriendId(friendId);
            friend.setCreated(System.currentTimeMillis());
            mongoTemplate.save(friend);
        }
        Query query2 = Query.query(Criteria.where("useId").is(friendId).and("friendId").is(userId));
        Friend friend2 = mongoTemplate.findOne(query2, Friend.class);
        if (friend2 == null){
            Friend friend = new Friend();
            friend.setUserId(friendId);
            friend.setFriendId(userId);
            friend.setCreated(System.currentTimeMillis());
            mongoTemplate.save(friend);
        }
    }

    /**
     * 获取当前用户好友id
     *
     * @param userId
     * @return
     */
    @Override
    public List<Friend> findByUserId(Long userId) {
        Query query = Query.query(Criteria.where("userId").is(userId));
        return mongoTemplate.find(query, Friend.class);
    }

    /**
     * 删除联系人
     *
     * @param userId
     * @param unlikeUserId
     */
    @Override
    public void deleteFriend(Long userId, Long unlikeUserId) {
        //查询用户与不喜欢用户数据
        Query query1 = Query.query(Criteria.where("userId").is(userId).and("friendId").is(unlikeUserId));
        Friend friend1 = mongoTemplate.findOne(query1, Friend.class);
        if (friend1 != null){
            //删除关联关系
            mongoTemplate.remove(query1,Friend.class);
        }
        Query query2 = Query.query(Criteria.where("userId").is(unlikeUserId).and("friendId").is(userId));
        Friend friend2 = mongoTemplate.findOne(query2, Friend.class);
        if (friend2 != null){
            //删除关联关系
            mongoTemplate.remove(query2,Friend.class);
        }
    }
}
